
package com.sky.controller.user;


import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.sky.constant.JwtClaimsConstant;
import com.sky.context.BaseContext;
import com.sky.dto.UpdateUserDTO;
import com.sky.dto.UserLoginDTO;
import com.sky.dto.UserLoginDTO1;
import com.sky.entity.SysUser;
import com.sky.exception.BizException;
import com.sky.exception.ExceptionEnum;
import com.sky.properties.JwtProperties;
import com.sky.result.Result;
import com.sky.service.ISysUserService;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO1;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.ExampleObject;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户信息表 前端控制器
 * </p>
 *
 * @author llj
 * @since 2025-01-17
 */

@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
@Tag(name = "用户信息表控制器接口", description = "SysUserControllerAPI")
@Slf4j
public class SysUserController {

    private final ISysUserService sysUserService;

    @Autowired
    private JwtProperties jwtProperties;

/**
     * 用户微信登入
     */

    @Operation(summary = "用户登入",
            description = "用户先进行微信登入",
            requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(
                    description = "用户登录DTO",
                    content = @Content(
                            mediaType = "application/json",
                            schema = @Schema(implementation = UserLoginDTO.class),
                            examples = @ExampleObject(
                                    value = "{\n" +
                                            "  \"code\": \"1234\"\n" +
                                            "}"
                            )
                    )
            )/*,
            responses = {
                    @ApiResponse(responseCode = "200", description = "登入成功", content = @Content(schema = @Schema(implementation = UserLoginVO1.class))),
                    @ApiResponse(responseCode = "1001", description = "未绑定身份信息，请进行学号绑定", content = @Content(schema = @Schema(implementation = String.class)))
            }*/
    )
    @PostMapping("/login/wx")
    public Result<UserLoginVO1> wxlogin(@RequestBody UserLoginDTO1 userLoginDTO) throws BizException {
        log.info("微信用户登录：{}", userLoginDTO.getCode());

        // 微信登录
        SysUser user = sysUserService.wxLogin(userLoginDTO); // 后续步骤实现

        // 为用户生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getUserId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

         UserLoginVO1 userLoginVO = UserLoginVO1.builder()
                .id(user.getUserId())
                .openid(user.getOpenid())
                .token(token)
                .build();
        return Result.success(userLoginVO);
    }

    @Operation(summary = "更新用户信息",
            requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(
                    description = "用户信息更新DTO"
            )
        /*    responses = {
                    @ApiResponse(responseCode = "200", description = "更新成功", content = @Content(schema = @Schema(implementation = SysUser.class))),
                    @ApiResponse(responseCode = "1003", description = "用户不存在", content = @Content(schema = @Schema(implementation = String.class)))
            }*/
    )
    @PutMapping("/userInfo")
    public Result<SysUser> updateUser(@RequestBody UpdateUserDTO updateUserDTO) {
        SysUser sysUser = sysUserService.getById(BaseContext.getCurrentId());
        if (sysUser == null) {
            throw new BizException(ExceptionEnum.USER_UPDATE_NOT_EXIST);
        }
        UpdateWrapper<SysUser> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_id", sysUser.getUserId());

        updateWrapper.set("update_time", LocalDateTime.now());
        // 使用UpdateWrapper只更新不为空的字段
        if (updateUserDTO.getNickName() != null) {
            updateWrapper.set("nick_name", updateUserDTO.getNickName());
        }
        if(updateUserDTO.getIntroduction() != null){
            updateWrapper.set("introduction", updateUserDTO.getIntroduction());
        }
        if (updateUserDTO.getSex() != null) {
            updateWrapper.set("sex", updateUserDTO.getSex());
        }
        if (updateUserDTO.getAvatar() != null) {
            updateWrapper.set("avatar", updateUserDTO.getAvatar());
        }


        sysUserService.update(updateWrapper);

        // 重新获取更新后的用户信息
        SysUser updatedUser = sysUserService.getById(sysUser.getUserId());
        return Result.success(updatedUser);
    }

    //查询用户信息
    @Operation(summary = "查询用户信息",
            description = "查询用户信息"
    )
    @GetMapping("/userInfo")
    public Result<SysUser> getUserInfo() {
        SysUser sysUser = sysUserService.getById(BaseContext.getCurrentId());
        if (sysUser == null) {
            throw new BizException(ExceptionEnum.USER_UPDATE_NOT_EXIST);
        }
        return Result.success(sysUser);
    }
}

